import FYBaseNode from "./FYBaseNode";
import FYMessenger from "./FYMessenger";
import FYUIMgr from "./FYUIMgr";

const { ccclass, property } = cc._decorator;

/** 窗口动画 */
export enum FYBaseUI_TweenType {
    /** 没有动画 */
    Node,
    /** 缩放动画 */
    Scale,
}

/**
 * 界面基类
 */
@ccclass
export default class FYBaseUI extends FYBaseNode {
    /** 设置Widget节点 */
    @property(cc.Node)
    public nodeWidget: cc.Node = null;
    /** 显示动画 */
    @property({ type: cc.Enum(FYBaseUI_TweenType), displayName: "窗口显示动画" })
    public showTweenType: FYBaseUI_TweenType = FYBaseUI_TweenType.Scale;
    /** 隐藏动画 */
    @property({ type: cc.Enum(FYBaseUI_TweenType), displayName: "窗口隐藏动画" })
    public hideTweenType: FYBaseUI_TweenType = FYBaseUI_TweenType.Scale;

    /**
     * 设置节点激活状态
     * @param bActive 是否激活
     */
    setActive(bActive) {
        if (this.nodeWidget) {
            this.nodeWidget.active = bActive;
        }
    }

    addListener() {
        super.addListener();
        FYMessenger.Instance.add(this.node.name, this.onShow, this);
    }

    removeListener() {
        super.removeListener();
        FYMessenger.Instance.remove(this.node.name, this.onShow, this);
    }

    /** 播放显示缓动动画 */
    playShowTween(cb: Function) {
        this.nodeWidget.scale = 0;
        let scaleAction = cc.scaleTo(0.3, 1.0).easing(cc.easeBackOut());
        let cbAction = cc.callFunc(function () {
            if (cb) {
                cb();
            }
        });
        let seq = cc.sequence(scaleAction, cbAction);
        this.nodeWidget.stopAllActions();
        this.nodeWidget.runAction(seq);
    }

    /** 播放隐藏缓动动画 */
    playHideTween(cb: Function) {
        this.nodeWidget.scale = 1;
        let scaleAction = cc.scaleTo(0.3, 0).easing(cc.easeBackIn());
        let cbAction = cc.callFunc(function () {
            if (cb) {
                cb();
            }
        });
        let seq = cc.sequence(scaleAction, cbAction);
        this.nodeWidget.stopAllActions();
        this.nodeWidget.runAction(seq);
    }

    /** 关闭 */
    close() {
        let self = this;
        if (this.hideTweenType === FYBaseUI_TweenType.Scale) {
            this.playHideTween(() => {
                FYUIMgr.Instance.close(self.node.name);
            })
        } else {
            FYUIMgr.Instance.close(self.node.name);
        }

    }

    // ------------------------------ 回调函数 ------------------------------- //

    onShow(param) {
        let self = this;
        if (this.showTweenType === FYBaseUI_TweenType.Scale) {
            this.playShowTween(null);
        }
    }

    // ------------------------------ 生命周期 -------------------------------- //

    start() {

    }
}